package com.spring.security;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.spring.authManage.dao.UserInfoDao;
import com.spring.authManage.pojo.UserInfo;
import com.spring.common.constant.StatusConstant;


@Service
public class CustomUserDetailsService implements UserDetailsService {
	private static Logger logger=Logger.getLogger(CustomUserDetailsService.class);
	@Autowired
	private UserInfoDao userInfoDao;
	/**
	 * 根据登陆的用户名加载用户的所有角色权限
	 * @param
	 * @return
	 * @throws Exception
	 */
	@Override
	public UserDetails loadUserByUsername (String userName) throws UsernameNotFoundException{
		UserInfo userInfo = new UserInfo();
		try {
			userInfo = userInfoDao.queryUserInfoByUserName(userName);
		} catch (Exception e) {
			logger.error("数据库不存在该用户:"+userName);
		}		
		//加层判断
		if(userInfo==null || userInfo.getPassword()==null||userInfo.getPassword().equals("")){
			throw new UsernameNotFoundException("Can't find the user "+userName);
		}
		if(userInfo.getStatus().equals(StatusConstant.N)){
			throw new UsernameNotFoundException(" Invalid user "+userName);
		}
		Set<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(userInfo.getRoleNameList());
		UserDetails userDetails = new User(userName, userInfo.getPassword(), true, true, true, true,grantedAuths);
		MDC.put("username", userDetails.getUsername());
		return userDetails;
	}
	private Set<GrantedAuthority> obtionGrantedAuthorities(List<String> roleNameList) {
		Set<GrantedAuthority> set = new HashSet<GrantedAuthority>();
		if (roleNameList!=null && roleNameList.size()>0){
			for (String roleName : roleNameList) {
				set.add(new SimpleGrantedAuthority(roleName));
			}	
		}
		return set;
	}
}